<?php
/**
 * Description: 获取每日一面信息
 * User: devforma
 * Date: 16/3/7
 * Time: 09:56
 */

require_once __DIR__ . '/includes/utils.php';

class GetInterviews implements iController {

    const MAX_NUM = 15;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        $isloggedIn = validateUser($queryArgs) === 1;

        if (empty($queryArgs['count']) || !filter_var($queryArgs['count'], FILTER_VALIDATE_INT)) {
            return genOutput(1000);
        }

        //限制列表最大数量
        $count = min($queryArgs['count'], self::MAX_NUM);

        $sql = 'SELECT `id`, `qid`, `releasedate` FROM `data_interview_userlist` WHERE 1';

        //如果给定了base_id,则按照base_id进行排序获取数据
        if (!empty($queryArgs['base_id']) && filter_var($queryArgs['base_id'], FILTER_VALIDATE_INT)) {
            $sql .= " AND `id`<={$queryArgs['base_id']}";
        }

        $sql .= " ORDER BY `id` DESC LIMIT {$count}";

        //获取题目列表
        $questions = $cmsdb->getResults($sql);

        $qids = array();
        foreach ($questions as $q) {
            $qids[] = $q->qid;
        }

        //获取赞数最多的答案
        $mostHotAnswers = $this->getMostHotAnswers($qids);

        if ($isloggedIn && $this->checkPurchase($queryArgs['user_id'])) {
            //获取我的答案
            $myAnswers = $this->getMyAnswers($qids, $queryArgs['user_id']);
        } else {
            $myAnswers = array();
        }

        //构造返回数据
        $list = array();
        foreach ($questions as $q) {
            $question = getInterviewDetail($q->qid);

            $new = array(
                'id' => intval($q->id),
                'question_id' => intval($q->qid),
                'date' => $q->releasedate,
                'content_text' => $question->subject,
                'limit_time' => intval($question->timelimit),
                'answer' => array(
                    'text' => $question->answer,
                    'duration' => intval($question->duration),
                    'file_url' => "http://edu-1.b0.upaiyun.com/interview/standard_answer/{$q->qid}/{$question->filename}",
                ),
                'hottest_answer' => array(
                    'user_id' => intval($mostHotAnswers[$q->qid]['user_id']),
                    'duration' => intval($mostHotAnswers[$q->qid]['duration']),
                    'file_url' => "http://edu-1.b0.upaiyun.com/interview/user_answer/{$mostHotAnswers[$q->qid]['user_id']}/{$q->qid}/{$mostHotAnswers[$q->qid]['filename']}"
                )
            );

            //获取用户答案
            if (isset($myAnswers[$q->qid]) && $myAnswers[$q->qid]['status']) {
                $new['my_answer'] = array(
                    'user_id' => intval($myAnswers[$q->qid]['user_id']),
                    'duration' => intval($myAnswers[$q->qid]['duration']),
                    'file_url' => "http://edu-1.b0.upaiyun.com/interview/user_answer/{$myAnswers[$q->qid]['user_id']}/{$q->qid}/{$myAnswers[$q->qid]['filename']}"
                );

            } else {
                $new['my_answer'] = new stdClass();
            }

            //获取收藏状态
            if (isset($myAnswers[$q->qid]) && $myAnswers[$q->qid]['is_collected']) {
                $new['is_collected'] = true;
            } else {
                $new['is_collected'] = false;
            }

            $list[] = $new;
        }

        return genOutput(1, array('list' => $list));
    }


    /**
     * 获取我的答案
     *
     * @param $qids
     * @param $userId
     * @return array
     */
    private function getMyAnswers($qids, $userId) {
        global $cmsdb;

        $string = implode(',', $qids);

        $data = $cmsdb->getResults("SELECT `qid`, `duration`, `filename`, `status`, `is_collected` FROM `data_interview_users` WHERE `uid`=:uid AND `qid` IN ({$string})",
            array(':uid' => $userId));

        $list = array();
        if (!empty($data)) {
            foreach ($data as $d) {
                $list[$d->qid] = array(
                    'user_id' => $userId,
                    'duration' => $d->duration,
                    'filename' => $d->filename,
                    'is_collected' => !empty($d->is_collected),
                    'status' => $d->status
                );
            }
        }

        return $list;
    }


    /**
     * 获取赞数最高的答案
     *
     * @param $qids
     * @return array
     */
    private function getMostHotAnswers($qids) {
        global $cmsdb;
        $string = implode(',', $qids);

        $data = $cmsdb->getResults("SELECT `qid`, MAX(`hot`), `uid`, `duration`, `filename` FROM `data_interview_users` WHERE `qid` IN ({$string}) AND `status`=1 GROUP BY `qid`");

        $list = array();
        foreach ($data as $d) {
            $list[$d->qid] = array(
                'user_id' => $d->uid,
                'duration' => $d->duration,
                'filename' => $d->filename
            );
        }

        return $list;
    }

    /**
     * 检测用户是否开启每日一面
     *
     * @param $userId
     * @return null|string
     */
    private function checkPurchase($userId) {
        global $cmsdb;

        return $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_id`=1128 AND `product_type`="interview"',
            array(':uid' => $userId));
    }
}